/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Bluetooth.java
 *
 * Created on 01-09-2009, 04:00:24 PM
 */

package secureplace;

//Para trabajar en segundo plano
import javax.swing.SwingWorker;

//Para programar la busqueda cada cierto tiempo
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

//Para remotedevicesdiscovery
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
/**
 *
 * @author hanscker
 */
public class Bluetooth extends javax.swing.JDialog {

    
    //static Vector dispositivosSeguros = new Vector();
        
    
    /** Creates new form Bluetooth */
    public Bluetooth() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        botonCerrar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(secureplace.SecurePlaceApp.class).getContext().getResourceMap(Bluetooth.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("Form"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.setName("jList1");
        jScrollPane1.setViewportView(jList1);
        jList1.setListData(secureplace.Bluetooth.RemoteDeviceDiscovery.DispositivosEncontrados);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jList2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList2.setName("jList2"); // NOI18N
        jScrollPane2.setViewportView(jList2);
        jList2.setListData(secureplace.Parametros.dispositivosSeguros);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jButton4.setText(resourceMap.getString("botonGuardar.text")); // NOI18N
        jButton4.setName("botonGuardar"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        botonCerrar.setText(resourceMap.getString("botonCerrar.text")); // NOI18N
        botonCerrar.setName("botonCerrar"); // NOI18N
        botonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCerrarActionPerformed(evt);
            }
        });

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1");

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botonCerrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4))
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel8)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(botonCerrar))
                .addContainerGap())
        );

        jTextField1.setText(secureplace.Parametros.Bluetooth_Intervalo);
        jLabel8.setText(secureplace.Bluetooth.RemoteDeviceDiscovery.DispositivoLocal());

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCerrarActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_botonCerrarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        secureplace.Bluetooth.RemoteDeviceDiscovery.RemoteDeviceDiscovery();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if ((secureplace.Parametros.dispositivosSeguros.contains(jList1.getSelectedValue())) == false) {
            secureplace.Parametros.dispositivosSeguros.addElement(jList1.getSelectedValue());
        }
        jList2.setListData(secureplace.Parametros.dispositivosSeguros);

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        secureplace.Parametros.Bluetooth_Intervalo = secureplace.Bluetooth.jTextField1.getText();
        secureplace.Parametros.guardarParametros();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        secureplace.Parametros.dispositivosSeguros.remove(jList2.getSelectedValue());
        jList2.setListData(secureplace.Parametros.dispositivosSeguros);
    }//GEN-LAST:event_jButton3ActionPerformed

    //Clase que realiza el trabajo de buscar los dispositivos bluetooth en segundo plano
    //private static BuscadorBluetooth buscadorBluetooth = new BuscadorBluetooth();
    
    static class BuscadorBluetooth extends SwingWorker<String, Void>{



        @Override
	protected String doInBackground() throws Exception {
		secureplace.Bluetooth.RemoteDeviceDiscovery.RemoteDeviceDiscovery();
		return "Operacion finalizada";
	}

        protected void process () {       
        }

        @Override
        protected void done() {
        }
    }

    static BuscadorBluetooth buscadorBluetooth = new BuscadorBluetooth();
    public static void buscarBluetooth () {
        buscadorBluetooth.execute();
    }

    /*
     *
     * Este metodo verifica si existen dispositivos seguros dentro de la
     * lista de dispositivos encontrados. Si existe alguno, entonces devuelve
     * la cantidad y entra en Modo Seguro. Si no
     * existe ningun dispositivo entonces entra en Modo Vigilancia*/
    static int dispositivosSegurosPresentes () {
        int cantidadDispositivosSegurosEncontrados = 0;
        int i, j = 0;
        for (i=0; i<secureplace.Parametros.dispositivosSeguros.size();i++ ) {
            for (j=0;j<RemoteDeviceDiscovery.DispositivosEncontrados.size();j++) {
                if (secureplace.Parametros.dispositivosSeguros.get(i).toString().contains(RemoteDeviceDiscovery.DispositivosEncontrados.get(j).toString())) {
                    cantidadDispositivosSegurosEncontrados++;
                }
            }
        }

        
        /*
         * Si hay algun dispositivo seguro presente o la cantidad de dispositivos seguros
         * configurados es distinta de 0  entonces entra en Modo Seguro
         */
        if ((cantidadDispositivosSegurosEncontrados>0) && (secureplace.Parametros.dispositivosSeguros.size()!=0))  {
            if (!secureplace.SecurePlaceApp.modo.equals("Seguro")) {
                secureplace.SecurePlaceApp.modo("Seguro");
            }
        //Si no hay ningun dispositivo seguro presente entonces entra en Modo Vigilancia
        } else {
            if (!secureplace.SecurePlaceApp.modo.equalsIgnoreCase("Vigilancia")) {
                secureplace.SecurePlaceApp.modo("Vigilancia");
            }
        }
        secureplace.SecurePlaceView.EtiquetaEstadoBluetooth.setText(cantidadDispositivosSegurosEncontrados + " dispositivo(s) seguro(s) encontrado(s)");
        return cantidadDispositivosSegurosEncontrados;
    }


    /*
     *
     * Esta clase implemeta un constructor que realiza la busqueda de dispositivos
     * bluetooth segun la configuracion de el intervalo de busqueda especificado
     * por el usuario*/
    static class RelojBluetooth{
    public RelojBluetooth(){
         // Modificar el tiempo de delay en milisegundos
         int intervalo = Integer.parseInt(secureplace.Parametros.Bluetooth_Intervalo) * 60000;
         Timer timer = new Timer (intervalo, new ActionListener ()
         {
             public void actionPerformed(ActionEvent arg0)
             {
                 // Aqui ejecuta la accion
                 buscadorBluetooth = new secureplace.Bluetooth.BuscadorBluetooth();
                 secureplace.Bluetooth.buscarBluetooth();
             }
         });
         timer.start();
    }
  }

    /**
     *
     * Esta clase realiza el proceso de busqueda de los dispositivos bluetooth y
     * los guarda como objetos en el vector DispositivosEncontados. Ademas
     * cambia algunos aspectos de la GUI cuando se encuentra efectuando una
     * busqueda e informa de los reultados.
     *
     * Por otra parte implementa un metodo que devuelve el dispositivo local
     * a través del cual se realizan las busquedas.
 */
    static class RemoteDeviceDiscovery extends SecurePlaceApp {


    public static final Vector DispositivosEncontrados = new Vector();

    /*
     * 
     * Metodo que devuelve el dispositivo local
     * a través del cual se realizan las busquedas.
     */
    public static String DispositivoLocal() {
        String dispositivoLocal = null;
                try {
                dispositivoLocal = LocalDevice.getLocalDevice().getFriendlyName() + " (" + LocalDevice.getLocalDevice().getBluetoothAddress() + ")";
                } catch (javax.bluetooth.BluetoothStateException e) {
                    System.out.println(e);
                }
                if (dispositivoLocal == null) {
                    dispositivoLocal = "Ninguno";
                }
                return dispositivoLocal;
    };

    public static void RemoteDeviceDiscovery() {

        final Object inquiryCompletedEvent = new Object();

        DispositivosEncontrados.clear();

        DiscoveryListener listener = new DiscoveryListener() {

            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                try {
                System.out.println("Dispositivo " + btDevice.getBluetoothAddress() + " " + btDevice.getFriendlyName(false));
                DispositivosEncontrados.addElement(btDevice.getBluetoothAddress() + " - " + btDevice.getFriendlyName(false));
                } catch (IOException e) {
                  System.out.println(e);
                }
            }

            public void inquiryCompleted(int discType) {
                System.out.println("Busqueda Bluetooth completada");

                synchronized(inquiryCompletedEvent){
                    inquiryCompletedEvent.notifyAll();
                }
                //Actualiza la lista de el formulario Bluetooth
                //jList1.setListData(secureplace.Bluetooth.RemoteDeviceDiscovery.DispositivosEncontrados);
                dispositivosSegurosPresentes();
            }

            public void serviceSearchCompleted(int transID, int respCode) {
            }

            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
            }

        };

        synchronized(inquiryCompletedEvent) {
            boolean started = false;
            try {
            started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
            } catch (javax.bluetooth.BluetoothStateException e) {
                secureplace.SecurePlaceView.EtiquetaEstadoBluetooth.setText("No se puede iniciar la busqueda");
                if (!secureplace.SecurePlaceApp.modo.equalsIgnoreCase("Vigilancia")) {
                    secureplace.SecurePlaceApp.modo("Vigilancia");
                    System.out.println(e);
                }
                
            }
            if (started) {
                    secureplace.SecurePlaceView.EtiquetaEstadoBluetooth.setText("Buscando...");
                    System.out.println("Buscando dispositivos bluetooth");
                    
                    try {
                    inquiryCompletedEvent.wait();
                    } catch (InterruptedException cantWaitCompletedEvent) {
                        System.out.println("No se puede esperar a completar la busqueda...");
                    }
                    
            }
        }
    }
}



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Bluetooth().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonCerrar;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private static javax.swing.JLabel jLabel8;
    private static javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    public static javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}